package com.xiaoyu.client.ui.activity.main.mine.my_order;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.techfansy.moreImageSelected.ImagePicker;
import com.techfansy.moreImageSelected.MoreImageMethod;
import com.techfansy.moreImageSelected.bean.ImageItem;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.seek.SelectedImgAdapter;
import com.xiaoyu.client.model.order.OrderBean;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.commonlib.BillionCardConstants;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivityWithTitle;
import com.xiaoyu.commonlib.ui.widget.ContainsEmojiEditText;
import com.xiaoyu.commonlib.ui.widget.RatingBar;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author jx
 * @date 创建时间 2018/11/7
 * @Description 评价
 */
public class EvaluateActivity extends BaseActivityWithTitle implements AdapterView.OnItemClickListener, SelectedImgAdapter.IDeleteSelectedListener {

    private View mView;
    private TextView mRightTxt;
    @BindView(R.id.activity_select_grid_view)
    GridView mGridView;
    @BindView(R.id.evaluate_content)
    ContainsEmojiEditText mContent;
    private SelectedImgAdapter mAdapter;
    private List<ImageItem> mList = new ArrayList<>();//选中的图片list
    private MoreImageMethod moreImageMethod;
    private ImagePicker imagePicker;

    @BindView(R.id.activity_evaluate_value)
    TextView mValue;
    @BindView(R.id.evaluate_ratingbar)
    RatingBar mRatingBar;
    private String orderId;//订单id
    private String goodsId;//商品id

    @Override
    protected void loadContentView(ViewGroup parent) {
        setTitleText("发表评论");
        mView = LayoutInflater.from(this).inflate(R.layout.activity_evaluate, parent, true);
        ButterKnife.bind(this);
        addRightTxt();
        initView();
        moreImageMethod = new MoreImageMethod();
        imagePicker = ImagePicker.getInstance();
        imagePicker.clear();
    }

    //添加右侧textview
    private void addRightTxt() {
        mRightTxt = new TextView(this);
        mRightTxt.setText("确定");
        mRightTxt.setTextSize(15);
        mRightTxt.setTextColor(Color.parseColor("#2796f0"));
        mRightTxt.setOnClickListener(this);
        addRightView(mRightTxt, 0);
    }

    private void initView() {
        OrderBean.DataBean.OrderParam orderParam = (OrderBean.DataBean.OrderParam) getIntent().getSerializableExtra(OrderFragment.ORDER_INFO);
        goodsId = orderParam.getGoodsid();
        orderId = orderParam.getOrderid();
        Log.i("jx", "orderid = " + orderId + "    goodsId = " + goodsId);
        mRatingBar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {

            @Override
            public void onRatingChange(float ratingCount) {
                mValue.setText(String.valueOf(ratingCount));
            }
        });

        mGridView.setOnItemClickListener(this);
        mAdapter = new SelectedImgAdapter(mList);
        mGridView.setAdapter(mAdapter);
        mAdapter.setIDeleteImg(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == mRightTxt) {
            if (TextUtils.isEmpty(mContent.getText().toString())) {
                ToastUtil.showToast(this, "请填写评价内容");
                return;
            }
            uploadImg();
        }

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        ActivityCompat.requestPermissions(EvaluateActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA}, 1);
        moreImageMethod.itemClick(EvaluateActivity.this, i, mList, imagePicker);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //接收回调的图片
        moreImageMethod.onActivityResult(requestCode, resultCode, data, imagePicker, mList, EvaluateActivity.this);
        mAdapter.upDataList(mList);
    }


    //上次发表评论
    private void uploadSendComment(String img) {
        NetworkManager.getSendComment(goodsId, PreferencesUtil.getString(PreferencesUtil.TOKEN, ""),
                mContent.getText().toString(), img, mValue.getText().toString(), mValue.getText().toString(), orderId, new CommonHttpResponser() {
                    @Override
                    public void onSuccess(String result) {
                        getOrderState("8");
                    }

                    @Override
                    public void onFailed(String errorCode, String errorDiscription) {
                    }
                });
    }


    //上传图片值OSS
    private void uploadImg() {
        for (int i = 0; i < mList.size(); i++) {
            uploadOSSUrl(mList.get(i).getPaths(), mList.get(i).getName(), i);
        }
    }

    private void uploadOSSUrl(String filePath, String objectKey, int position) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        try {
            OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
            PutObjectResult putResult = oss.putObject(put);
            if (position != mList.size() - 1) return;
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < mList.size(); i++) {
                builder.append("https://yikabangb.oss-cn-beijing.aliyuncs.com/" + mList.get(i).getName());
                builder.append(i != mList.size() - 1 ? "," : "");
            }

            uploadSendComment(builder.toString());//调取接口上传内容

        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
        }
    }


    //调取接口判断订单状态
    private void getOrderState(String orderstate) {
        NetworkManager.stateChange(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), orderId, orderstate, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                finish();
                Log.i("jx", "onSuccess: 确认收货" + result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                Log.i("jx", "onFailed:--- " + errorCode + errorDiscription);
            }
        });
    }

    @Override
    public void deleteImg(int position) {
        mList.remove(position);
        moreImageMethod.images.remove(position);
        mAdapter.upDataList(mList);
    }
}
